package main

import (
	"fmt"
	"sync/atomic"
	"time"
)

func main() {
	done := make(chan struct{})
	var num int32

	// 定时增加num的值
	go func() {
		defer func() {
			done <- struct{}{}
		}()
		for {
			time.Sleep(time.Millisecond * 500)
			newNum := atomic.AddInt32(&num, 1)
			fmt.Println("num:", newNum)
			if newNum > 10 {
				break
			}
		}
	}()
	
	// 定时检查num的值，如果等于10，就设置为0
	go func() {
		defer func() {
			done <- struct{}{}
		}()
		for {
			if atomic.CompareAndSwapInt32(&num, 10, 0) {
				fmt.Println("检查到num为10，清0")
				break
			}
			time.Sleep(time.Millisecond * 500)
		}
	}()

	<- done
	<- done
	fmt.Println("Over")
}